import { routerRedux } from 'dva/router';
import { fakeAccountLogin } from '../services/api';
import { setAuthority } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';
import { message } from 'antd'

export default {
  namespace: 'login',

  state: {
    status: undefined,
    isAdmin: false,
    userName: ""
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      console.log("login", response)
      const { result } = response;
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.status === 0) {
        reloadAuthorized();
        localStorage.setItem('userinfo', JSON.stringify(response.result));
        yield put(routerRedux.push({
          pathname: '/charge/code'
        }))
      } else if (response.status === -1) {
        message.error(`${response.message}`)
      }
    },

    *logout(_, { put, select }) {
      try {
        // get location pathname
        const urlParams = new URL(window.location.href);
        const pathname = yield select(state => state.routing.location.pathname);
        // add the parameters in the url
        urlParams.searchParams.set('redirect', pathname);
        window.history.replaceState(null, 'login', urlParams.href);
      } finally {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            result: { userAccount: 'guest' },
          },
        });
        reloadAuthorized();
        yield put(routerRedux.push('/user/login'));
      }
    },

  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload.result) {
        setAuthority(payload.result.userAccount);
      } else {
        setAuthority(null);
      }
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        isAdmin:payload.result && payload.result.userAccount == 'admin' ? true : false,
        userName:payload.result && payload.result.userName
      };
    },
  },
};
